#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    tcpSocket = new QTcpSocket;
    tcpSocket->connectToHost("114.55.253.104", 6666);
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(recv()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_name_returnPressed()
{
    name = ui->name->text().toStdString();
    ui->pushButton->setEnabled(true);
    ui->name->deleteLater();
}

void Widget::on_pushButton_clicked()
{
    std::string msg = name;
    std::string str = ui->input->text().toStdString();
    msg.append(":");
    msg.append(str);
    tcpSocket->write(msg.c_str(), msg.size()+1);
    ui->input->clear();
}

void Widget::recv()
{
    char buf[256] = {};
    tcpSocket->read(buf, sizeof(buf));
    ui->show->append(buf);
}

void Widget::closeEvent(QCloseEvent *)
{
    std::string str = name;
    str.append(":quit");
    tcpSocket->write(str.c_str(), str.size()+1);
}
